package maple.thelittleredbook.recommendation.controller;

import lombok.extern.slf4j.Slf4j;
import maple.thelittleredbook.common.dto.ApiResponse;
import maple.thelittleredbook.common.service.AuthService;
import maple.thelittleredbook.content.dto.ContentViewDTO;
import maple.thelittleredbook.logging.annotation.SystemLog;
import maple.thelittleredbook.recommendation.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 推荐控制器
 * 负责为用户提供个性化内容推荐
 */
@Slf4j
@RestController
@RequestMapping("/api/recommendations")
public class RecommendationController {

    private final RecommendationService recommendationService;
    private final AuthService authService;

    @Autowired
    public RecommendationController(RecommendationService recommendationService,
                                    AuthService authService) {
        this.recommendationService = recommendationService;
        this.authService = authService;
    }

    /**
     * 获取下一个推荐内容
     * 基于用户画像和行为历史的个性化推荐算法
     */
    @GetMapping("/next")
    @SystemLog(operation = "获取推荐内容")
    public ResponseEntity<ApiResponse<ContentViewDTO>> getNextRecommendation() {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户请求推荐内容，用户ID: {}", userId);

        try {
            // 获取推荐内容
            ContentViewDTO recommendation = recommendationService.getNextRecommendation(userId);

            if (recommendation == null) {
                log.info("暂无推荐内容，用户ID: {}", userId);
                return ResponseEntity.ok(ApiResponse.fail("暂无推荐内容，请稍后再试"));
            }

            log.info("推荐内容获取成功，用户ID: {}, 内容ID: {}, 标题: {}",
                    userId, recommendation.getId(), recommendation.getTitle());

            return ResponseEntity.ok(ApiResponse.success("推荐内容获取成功", recommendation));

        } catch (Exception e) {
            log.error("获取推荐内容失败，用户ID: {}", userId, e);
            return ResponseEntity.ok(ApiResponse.fail("获取推荐内容失败，请稍后重试"));
        }
    }
}